package com.seio.edc.controller.policy;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.nova.edc.model.system.PolicyEntity;
import com.seio.edc.common.Constants;
import com.seio.edc.util.FileUtil;

/**
 * 项目政策
 * 
 * @author Administrator
 * 
 */
@Controller
public class PolicyContoller {

	private static Logger log = Logger.getLogger(PolicyContoller.class);

	/**
	 * 相关政策初始化
	 * 
	 * @return
	 */
	@RequestMapping(value = "policyInit")
	public ModelAndView policyInit(HttpServletRequest request, ModelMap map) {
		List<PolicyEntity> list = new ArrayList<PolicyEntity>();
		List<String> fileNames = FileUtil
				.getAllFileNames(Constants.UploadFilsPath);
		for (int i = 0; i < fileNames.size(); i++) {
			PolicyEntity tmp = new PolicyEntity();
			tmp.setFileName(fileNames.get(i));
			list.add(tmp);
		}
		map.put("list", list);

		// map.put("msg", "");
		return new ModelAndView("policy/policy", map);
	}

	/**
	 * 政策信息上传
	 * 
	 * @param request
	 * @param modelMap
	 * @param search
	 * @return
	 */
	@RequestMapping(value = "fileUpload")
	public ModelAndView fileUpload(HttpServletRequest request, ModelMap modelMap) {

		try {
			// 设置上下方文
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());

			// 检查form是否有enctype="multipart/form-data"
			if (multipartResolver.isMultipart(request)) {
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					// 由CommonsMultipartFile继承而来,拥有上面的方法.
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						String path = Constants.UploadFilsPath
								+ file.getOriginalFilename();

						File localFile = new File(path);
						file.transferTo(localFile);
					}
				}
			}
			modelMap.put("msg", "文件上传成功！");
		} catch (Exception e) {
			log.error("文件上传失败：" + e.getStackTrace());
			modelMap.put("msg", "文件上传失败！");
		}

		return policyInit(request, modelMap);
	}

	/**
	 * 政策信息下载
	 * 
	 * @param request
	 * @param modelMap
	 * @param search
	 * @return
	 */
	@RequestMapping(value = "fileDownload")
	public String fileDownload(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			response.setContentType("text/html;charset=UTF-8");
			request.setCharacterEncoding("UTF-8");

			String fileName = request.getParameter("filename");
			String downLoadPath = Constants.UploadFilsPath + fileName;

			long fileLength = new File(downLoadPath).length();

			response.setContentType("application/octet-stream");
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String(fileName.getBytes("utf-8"), "iso8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));

			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
				bos.flush();
			}
			bis.close();
			bos.close();

		} catch (Exception e) {
			log.error(e.getStackTrace());
			modelMap.put("msg", "文件下载失败！");
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

		return null;
	}

	@RequestMapping(value = "checkFileName.shtml")
	@ResponseBody
	public Map<String, Object> checkFileName(HttpServletRequest request,
			@RequestBody String fileName) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (fileName != null && fileName.contains("\\")) {
			int beginIndex = fileName.lastIndexOf("\\") + 1;
			fileName = fileName.substring(beginIndex);
		}
		String downLoadPath = Constants.UploadFilsPath + fileName;
		File file = new File(downLoadPath);
		if (file.exists()) {
			map.put("existFlag", true);
		} else {
			map.put("esistFlag", false);
		}

		return map;
	}

}
